package org.linphone.sub.utils;

import android.util.Log;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Xiang on 2018/3/19.
 */

public class SocketUtil {

	/**
	 * 将16进制字符串转换为byte
	 *
	 * @param str
	 * @return
	 */
	public static byte toByte(String str) {
		if(str == null || str.trim().equals("")) {
			return 0;
		}

		return (byte) Integer.parseInt(str, 16);

	}

	/**
	 * 将16进制字符串转换为byte[]
	 *
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		if(str == null || str.trim().equals("")) {
			return new byte[0];
		}

		byte[] bytes = new byte[str.length() / 2];
		for(int i = 0; i < str.length() / 2; i++) {
			String subStr = str.substring(i * 2, i * 2 + 2);
			bytes[i] = (byte) Integer.parseInt(subStr, 16);
		}

		return bytes;
	}


	/**
	 * byte数组中取int数值，本方法适用于(低位在前，高位在后)的顺序，和和intToBytes（）配套使用
	 *
	 * @param src
	 *            byte数组
	 * @return int数值
	 */
	public static int byteToInt(byte src) {
		int value;
		value = ((src & 0xFF));
		return value;
	}

	//高位在前，低位在后
	public static byte[] int2bytes(int num){
		byte[] result = new byte[2];
		result[0] = (byte)((num >>> 8) & 0xff);
		result[1] = (byte)((num)& 0xff );
		return result;
	}

	/**
	 * byte数组中取int数值，本方法适用于(低位在后，高位在前)的顺序。和intToBytes2（）配套使用
	 */
	public static int bytesToInt2(byte first, byte second) {
		int value;
		value = (((first & 0xFF)<<8)
				|(second & 0xFF));
		return value;
	}


	public static int byteArrayToInt(byte[] b){
		byte[] a = new byte[4];
		int i = a.length - 1,j = b.length - 1;
		for (; i >= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据
			if(j >= 0)
				a[i] = b[j];
			else
				a[i] = 0;//如果b.length不足4,则将高位补0
		}
		int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
		int v1 = (a[1] & 0xff) << 16;
		int v2 = (a[2] & 0xff) << 8;
		int v3 = (a[3] & 0xff) ;
		return v0 + v1 + v2 + v3;
	}

	public static String bytesToHexString(byte[] src , int startIndex,int stopIndex){
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = startIndex; i < stopIndex; i = i+2) {
			stringBuilder.append("\\u");
			int v = src[i+1] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);

			int u = src[i] & 0xFF;
			String hu = Integer.toHexString(u);
			if (hu.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hu);
		}
		return stringBuilder.toString();
	}

	//byte转为16进制
	public static String byteToHexString(byte b){
		StringBuilder str = new StringBuilder("");
		int v = b & 0xFF;
		String hv = Integer.toHexString(v);
		if(hv.length() < 2){
			str.append(0);
		}
		str.append(hv);

		return str.toString();
	}

	//Unicode转中文
	public static String unicode2String(String asciicode) {

		String[] asciis = asciicode.split ("\\\\u");
		String nativeValue = asciis[0];
		try
		{
			for ( int i = 1; i < asciis.length; i++ )
			{
				String code = asciis[i];
				nativeValue += (char) Integer.parseInt (code.substring (0, 4), 16);
				if (code.length () > 4)
				{
					nativeValue += code.substring (4, code.length ());
				}
			}
		}
		catch (NumberFormatException e)
		{
			return asciicode;
		}
		return nativeValue;
	}


	public static byte[] hexToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}

		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] bytes = new byte[length];
		String hexDigits = "0123456789abcdef";
		for (int i = 0; i < length; i++) {
			int pos = i * 2; // 两个字符对应一个byte
			int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
			int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
			if(h == -1 || l == -1) { // 非16进制字符
				return null;
			}
			bytes[i] = (byte) (h | l);
		}
		return bytes;
	}

	//获取本机ip
	public static String getHostIp(){

		String hostIp = null;
		try {
			Enumeration nis = NetworkInterface.getNetworkInterfaces();
			InetAddress ia = null;
			while (nis.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) nis.nextElement();
				Enumeration<InetAddress> ias = ni.getInetAddresses();
				while (ias.hasMoreElements()) {
					ia = ias.nextElement();
					if (ia instanceof Inet6Address) {
						continue;// skip ipv6
					}
					String ip = ia.getHostAddress();
					if (!"127.0.0.1".equals(ip)) {
						hostIp = ia.getHostAddress();
						break;
					}
				}
			}
		} catch (SocketException e) {
			Log.i("yao", "SocketException");
			e.printStackTrace();
		}
		return hostIp;

	}
}
